package org.java.user.controller;

import org.java.commons.vo.Result;
import org.java.user.api.damain.User;
import org.java.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/profile")
public class ProfileController {
    @Autowired
    private UserService userService;
    //显示用户信息页面
    @GetMapping
    public ModelAndView profile(@AuthenticationPrincipal OAuth2Authentication authentication){
        String id = authentication.getName();
        User user = userService.findById(id);
        ModelAndView mav = new ModelAndView("profile");
        mav.addObject("user",user);
        return mav;
    }

    @PostMapping(produces = "application/json")
    @ResponseBody
    public Result saveJson(@AuthenticationPrincipal OAuth2Authentication authentication,
                           //把整个请求体作为对象的内容，表单提交的 则使用默认的，json提交的就需要使用此注解
                           @RequestParam User user) {
        String id = authentication.getName();
        user.setId(id);
        return  this.userService.save(user);
    }

    @PostMapping()
    public ModelAndView saveHtml(@AuthenticationPrincipal OAuth2Authentication authentication, User user) {
        Result result = this.saveJson(authentication, user);
        // 视图名称如果有 redirect: 开头，表示重定向
        // 注意：默认情况下，网关代理的时候，不会修改重定向的响应头，导致重定向以后，会直接访问下游服务。
        // 浏览器直接访问下游服务，是没有授权信息的。
        ModelAndView mav = new ModelAndView();
        mav.addObject("result",result);
        if (result.getCode() == 1){
            mav.setViewName("redirect:./profile");
        }else{
            mav.setViewName("/profile");
        }
        return mav;
    }
}
